#!/usr/bin/env bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

usage()
{ #[[[
    echo "Usage: $(basename $0) [-t mp3|ogg] file(ape|flac)"
} #]]]

main()
{ #[[[
    while getopts 't:' opt
    do
        case $opt in
            t)
                encode=$OPTARG
                case $encode in
                    mp3)
                        encode_cmd="lame --preset extreme -"
                        ;;
                    ogg)
                        encode_cmd="oggenc -q 8 - -o"
                        ;;
                    *)
                        usage
                        return
                        ;;
                esac
                ;;
            *)
                usage
                return
                ;;
        esac
    done
    if [[ -z $encode ]]
    then
        encode=mp3
        encode_cmd="lame --preset extreme -"
    fi

    shift $(($OPTIND-1))
    if (( $# == 0 ))
    then
        usage
        return
    fi

    while (( $# > 0 ))
    do
        file=$1
#        echo $file
        decompress=${file##*.}
#        echo $decompress
        case $decompress in
            ape)
                decompress_cmd="mac $file - -d"
                ;;
            flac)
                decompress_cmd="flac -d $file -"
                ;;
            *)
                usage
                return
                ;;
        esac
        filename=${file%.*}
        cmd="$decompress_cmd | $encode_cmd ${filename}.${encode}"
        echo $cmd
        eval $cmd
        shift
    done
} #]]]

main "$@"
